/**
 @Name：文章管理
 @Author：cike
 @Date：2019-5-26
**/

layui.define(['table', 'form','treeGrid','colorpicker','layedit','upload'], function(exports){
  var $ = layui.$
  ,admin = layui.admin
  ,view = layui.view
  ,table = layui.table
  ,setter = layui.setter
  ,form = layui.form
  ,treeGrid = layui.treeGrid
  ,colorpicker = layui.colorpicker
  ,layedit = layui.layedit
  ,upload = layui.upload;

  upload.set({
    data:{
      access_token: layui.data(setter.tableName)[setter.request.tokenName]
    }
    ,size:1024
  });

  layedit.set({
    tool: ["strong", "italic", "underline", "del", "|", "left", "center", "right", "|", "link", "unlink", "face", "image","code"]
    ,uploadImage:{
      url: setter.api_back_image_upload //接口url
    }
    ,height:300
  });

  treeGrid.set({
    where: {
      access_token: layui.data(setter.tableName)[setter.request.tokenName]
    }
    ,method: 'post'
    ,response:{
      statusCode: 200
    }
    ,page: true
    ,text: { none : "暂无相关数据" }
    ,done: function (res) {
      if(res[setter.response.statusCode] == setter.response.statusCode.logout){
        view.exit();
      }
    }
    ,parseData: function(res){ //res 即为原始返回的数据
      return {
        "code": res.code, //解析接口状态
        "msg": res.msg, //解析提示文本
        "count": res.data.total, //解析数据长度
        "data": res.data.list //解析数据列表
      };
    }
  });

  // table设置
  table.set({
    where: {
      access_token: layui.data(setter.tableName)[setter.request.tokenName]
    }
    ,method: 'post'
    ,response:{
      statusCode: 200
    }
    ,request:{
      pageName: "page"
      ,limitName: "size"
    }
    ,page: true
    ,text: { none : "暂无相关数据" }
    ,done: function (res) {
      if(res[setter.response.statusCode] == setter.response.statusCode.logout){
        view.exit();
      }
    }
    ,parseData: function(res){ //res 即为原始返回的数据
      return {
        "code": res.code, //解析接口状态
        "msg": res.msg, //解析提示文本
        "count": res.data.total, //解析数据长度
        "data": res.data.list //解析数据列表
      };
    }
  });

  //文章管理
  table.render({
    elem: '#back-article-list'
    ,url: setter.api_back_article_list
    ,cols: [[
      {field: 'id', width: 65, title: 'ID', sort: true,fixed: 'left'}
      ,{field: 'title', width: 200, title: '标题'}
      ,{field: 'type', width: 100, title: '类型'}
      ,{field: 'user_type', width: 100, title: '作者类型'}
      ,{field: 'user_name', width: 100, title: '作者名称'}
      ,{field: 'hot_level', width: 100, title: '推荐等级',
        templet: function(d){
          return  d.hot_level == 3 ? '<span style="color: #FF5722;">置顶</span>' :
                  d.hot_level == 2 ? '<span style="color: #5FB878;">推荐</span>' :
                  '<span style="color: #666;">普通</span>'
        }
      }
      ,{field: 'comment_status', width: 100, title:'评论状态', templet: '#comment_status_switch', minWidth: 80, align: 'center'}
      ,{field: 'status', width: 100, title:'显示状态', templet: '#status_switch', minWidth: 80, align: 'center'}
      ,{field: 'update_time', width : admin.screen() < 2 ? 160 : '', title: '更新时间'}
      ,{field: 'create_time', width : admin.screen() < 2 ? 160 : '', title: '创建时间'}
      ,{title: '操作', width: 150, align: 'center', toolbar: '#back-article-list-operation'}
    ]]
  });

  //监听工具条
  table.on('tool(back-article-list)', function(obj){
    var data = obj.data;
    if(obj.event === 'del'){
      layer.confirm('确定删除此文章？', function(index){
        admin.req({
          url: setter.api_back_article_delete
          ,data: {id:data.id}
          ,done: function(res){
            layer.msg(res.msg);
            layer.close(index); //执行关闭 
            table.reload('back-article-list'); //重载表格
          }
        });
      });
    }else if(obj.event === 'edit'){
      admin.popup({
        title: '编辑文章'
        ,area: admin.screen() < 2 ? ['100%','600px'] : ['710px','880px']
        ,maxmin: true
        ,id: 'back-article-edit-popup'
        ,success: function(layero, index){
          view(this.id).render('article/form',data).done(function(){
            // 富文本编辑器
            var layeditInst2 = layedit.build('myEditor');
            // 封面上传
            var uploadInst = upload.render({
              elem: '#upload-cover'
              ,url: setter.api_back_image_upload
              ,before: function(obj){
                obj.preview(function(index, file, result){
                  $('#upload-cover-img').attr('src', result); //图片链接（base64）
                });
              }
              ,done: function(res){
                if(res.code > 0){
                  return layer.msg('上传失败');
                }else{
                  $('#upload-cover-input').val(res.data.src);
                }
              }
              ,error: function(){
                var text = $('#upload-cover-text');
                text.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini reload">重试</a>');
                text.find('.reload').on('click', function(){
                  uploadInst.upload();
                });
              }
            });
            // 类型下拉框
            admin.req({
              url: setter.api_back_article_type_list
              ,done: function(res){
                var select = $('#back-article-form-type-select');
                var code = [];
                $.each(res.data.list, function (index, item) {

                  if(item.pid == 0){
                    code[item.id] = '<optgroup label="'+item.name+'">';
                  }else{
                    is_select = item.id == data.type_id ? 'selected':'';
                    code[item.pid] = code[item.pid] + '<option value="'+item.id+'" '+is_select+'>'+item.name+'</option>';
                  }
                });
                $.each(code, function (index, item) {
                  if(item){
                    select.append(item + "</optgroup>");
                  }
                });
                form.render(null, 'back-article-form');
              }
            });
            //监听提交
            form.on('submit(back-article-form-submit)', function(data){
              var field = data.field; //获取提交的字段
              field.status = field.status?1:0;
              field.comment_status = field.comment_status?1:0;
              field.content = layedit.getContent(layeditInst2);
              admin.req({
                url: setter.api_back_article_update
                ,data: field
                ,done: function(res){
                  layer.msg(res.msg);
                  layer.close(index); //执行关闭 
                  table.reload('back-article-list'); //重载表格
                }
              });
            });
            $('#layer-close').on('click', function(event) {
              layer.close(index); //执行关闭 
              /* Act on the event */
            });
          });
        }
      });
    }
  });



  // 文章类型
  treeGrid.render({
    id:'back-article-type-list'
    ,elem: '#back-article-type-list'
    ,url:setter.api_back_article_type_list
    ,cellMinWidth: 100
    ,idField:'id'//必須字段
    ,treeId:'id'//树形id字段名称
    ,treeUpId:'pid'//树形父id字段名称
    ,treeShowName:'name'//以树形式显示的字段
    // ,height:600
    ,isFilter:false
    ,iconOpen:false
    ,isOpenDefault:true//节点默认是展开还是折叠【默认展开】
    ,loading:true
    ,isPage:false
    ,limit:999
    ,cols: [[
        {field:'id', width: 65, title: '编号'}
        ,{field:'pid', width: 65, title: '上级'}
        ,{field:'sort', width: 65, title: '排序', edit:'text'}
        ,{field:'name', title: '名称' ,width: 150}
        ,{field:'update_time', title: '更新时间'}
        ,{field:'create_time', title: '创建时间'}
        ,{title:'操作', width: 150, align: 'center', toolbar: '#back-article-type-list-operation'}
    ]]
  });
  //监听工具条
  treeGrid.on('edit(back-article-type-list)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
    admin.req({
      url: setter.api_back_article_type_update
      ,data: obj.data
      ,type: 'post'
      ,done: function(res){
        layer.msg(res.msg);
        treeGrid.reload('back-article-type-list'); //重载表格
      }
    });
  });
  treeGrid.on('tool(back-article-type-list)', function(obj){
    var data = obj.data;
    if(obj.event === 'del'){
      layer.confirm('确定删除此类型？', function(index){
        admin.req({
          url: setter.api_back_article_type_delete
          ,data: {id:obj.data.id}
          ,type: 'post'
          ,done: function(res){
            layer.msg(res.msg);
            treeGrid.reload('back-article-type-list'); //重载表格
          }
        });
        layer.close(index); //执行关闭 
      });
    }else if(obj.event === 'edit'){
      admin.popup({
        title: '编辑类型'
        ,area: admin.screen() < 2 ? ['100%','320px'] : ['450px','320px']
        ,id: 'back-article-type-edit-popup'
        ,success: function(layero, index){
          view(this.id).render('article/typeform', data).done(function(){
            // 上级选择
            console.log(data);
            admin.req({
              url: setter.api_back_article_type_list
              ,done: function(res){
                var list = res.data.list;
                list.unshift({"id":0,"pid":0,"name":"空"})
                $.each(list, function (index, item) {
                  if(item.pid == 0 && item.id != data.id){
                    is_checked = item.id == data.pid?'checked':'';
                    $('#back-article-type-form-type-select').append(new Option(item.name, item.id, is_checked, is_checked));// 下拉菜单里添加元素
                  }
                });
                form.render(null, 'back-article-type-form');
              }
            });
            //监听提交
            form.on('submit(back-article-type-form-submit)', function(data){
              var field = data.field; //获取提交的字段
              admin.req({
                url: setter.api_back_article_type_update
                ,data: field
                ,type: 'post'
                ,done: function(res){
                  layer.msg(res.msg);
                  layer.close(index); //执行关闭
                  treeGrid.reload('back-article-type-list'); //重载表格
                }
              });
            });
            $('#layer-close').on('click', function(event) {
              layer.close(index); //执行关闭 
              /* Act on the event */
            });
          });
        }
      });
    }
  });



  


  exports('article', {})
});